package practice07;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Administrator
 * @version V1.0
 * @ProjectName:IntelliJ IDEA
 * @PackageName: PACKAGE_NAME
 * @ClassName: practice07.Server
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @date 2020/1/3 10:44
 * @Copyright 大牛版板所有
 */
public class Server {
    //存储所有客户端套接字
    private static List<Socket> clientSocketList = Collections.synchronizedList(new ArrayList<>());
    //使用线程池创建线程
    static ExecutorService executor = Executors.newFixedThreadPool(100);

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket clientSocket = null;
        try {
            serverSocket = new ServerSocket(9000);
            System.out.println("服务器已启动");
            int num = 0;
            while (true){//启动服务，一直等待客户端请求
                clientSocket = serverSocket.accept();
                num++;
                clientSocketList.add(clientSocket);
                String remoteClientIP = clientSocket.getInetAddress().getHostAddress();
                int remoteClientPort = clientSocket.getPort();
                //第6个【192.168.10.32:8234】客户端与服务器连接成功
                System.out.println("第" + num +"个【"+remoteClientIP+":"+remoteClientPort+"】客户端与服务器连接成功");
                //了每一个成功与服务器建立连接的客户端专门开启一个新的工作线程为之服务
                executor.execute(new ServerThread(clientSocket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (clientSocket != null){
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class ServerThread implements Runnable{
        private Socket clientSocket = null;
        private BufferedReader reader = null;
        private PrintWriter writer = null;

        public ServerThread(Socket clientSocket){
            this.clientSocket = clientSocket;
        }
        @Override
        public void run() {
            try {
                reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                String message = reader.readLine();
                doDispatch(message);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (reader != null){
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        private void doDispatch(String message) {
            try {
                Iterator<Socket> socketIterator = clientSocketList.iterator();
                writer = new PrintWriter(clientSocket.getOutputStream(),true);
                while(socketIterator.hasNext()){
                    Socket tempSocket = socketIterator.next();
                    /*if(!clientSocket.equals(tempSocket)){
                        writer.println(message); //自己发的消息不要分发给自己了
                    }*/
                    writer.println(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (clientSocket != null){
                    try {
                        clientSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
